import 'package:PollOnLine/utils/EventBusUtils.dart';
import 'package:PollOnLine/utils/logger_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../bean/UserTaskCount.dart';
import '../../network/network.dart';
import 'home_state.dart';

// GetSingleTickerProviderStateMixin
class HomeLogic extends GetxController with GetSingleTickerProviderStateMixin {
  final HomeState state = HomeState();

  // https://www.soinside.com/question/Xy88ZsX4BuEJeMgJPi6QjU
  // https://www.jianshu.com/p/c89b93311178
  late TabController tabController;

  // late PageController pageController;
  late StreamSubscription<HomeEvent>? subscription;

  @override
  void onInit() {
    super.onInit();
    tabController = TabController(length: state.tabs.length, vsync: this);
    // pageController = PageController(viewportFraction: 0.999999 );
  }

  @override
  void onReady() {
    super.onReady();
    // tabController.addListener(tabIndexListener);
    tabController.animation?.addListener(tabIndexListener);
    // 监听刷新
    subscription = bus.listen((event) => getUserTaskCount());

    getUserTaskCount();
  }

  // 动画监听
  void tabAnimationListener() {
    if (tabController.offset >= 0.5 || tabController.offset <= -0.5) {
      state.choose.value = tabController.index;
      update();
    }
  }

  // index监听
  void tabIndexListener() {
    state.choose.value = tabController.index;
    // pageController.jumpToPage(tabController.index);
    update();
  }

  // 判断是否被选择
  bool isChoose(int index) {
    return state.choose.value == state.tabs[index].id;
  }

  Future<void> getUserTaskCount() async {
    ResultData resultData = await Api.getUserTaskCount();
    if (resultData.isSuccess) {
      UserTaskCount userTaskCount = UserTaskCount.fromJson(resultData.data['data']);
      int completeCount = int.parse(userTaskCount.completeCount ?? '0');
      int taskEdCount = int.parse(userTaskCount.taskEdCount ?? '0');
      int taskIngCount = int.parse(userTaskCount.taskIngCount ?? '0');
      state.tabs[0] = Tabs(0, "全部任务", (completeCount + taskEdCount + taskIngCount).toString());
      state.tabs[1] = Tabs(1, "进行中的任务", taskIngCount.toString());
      state.tabs[2] = Tabs(2, "截止的任务", taskEdCount.toString());
      state.tabs[3] = Tabs(3, "已完成任务", completeCount.toString());
      update();
    }
  }

  @override
  void onClose() {
    super.onClose();
    subscription?.cancel();
  }
}
